<template>
  <div class="app-container">
    <el-dialog :close-on-click-modal="false" :visible.sync="open" append-to-body title="打印标签" width="550px">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="选择打印机">
          <el-select v-model="form.printCode" clearable @change="chosePrinter">
            <el-option
              v-for="item in printerList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="printContent">打印</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getLodop} from '@/utils/LodopFuncs';
import {printSignPdf} from "@/api/shipment/shipment";

let LODOP;

export default {
  name: 'PrintSign',
  data() {
    return {
      open: false,
      dataArray: [],
      form: {
        printCode: null,
      },
      printerList: [],
      fileAddress: null,
    }
  },
  methods: {
    reset() {
      this.form = {
        printCode: null,
      }
    },
    openDialog(ids) {
      this.reset()
      this.getPrinters()
      this.open = true;
      //获取文件地址
      this.fileAddress = ''
      printSignPdf(ids).then(res => {
        console.log(res.data)
        this.fileAddress = process.env.VUE_APP_BASE_API + '/common/download?fileName=' + res.data;
      })
    },
    getPrinters() {
      LODOP = getLodop()
      if (!LODOP) {
        this.$message.error('打印错误，请检查打印机是否安装正确！')
        return
      }
      this.printerList = []
      // 获取打印机个数
      let counter = LODOP.GET_PRINTER_COUNT()
      for (let i = 0; i < counter; i++) {
        this.printerList.push({
          // 将打印机存入printerList数组中
          name: LODOP.GET_PRINTER_NAME(i),
          value: i
        })
      }
      const printCode = this.form.printCode = this.$cache.local.get('print_sign')
      if (printCode) {
        this.form.printCode = parseInt(printCode)
      }
    },
    chosePrinter(v) {
      // 将printCode 放入 key 为 print_sign 的缓存
      if (v) {
        this.$cache.local.set('print_sign', v)
      }
    },
    printContent() {
      // 获取LODOP对象的主过程
      LODOP = getLodop()
      if (!LODOP) {
        this.$message.error('打印错误，请检查打印机是否安装正确！')
        return
      }
      LODOP.PRINT_INIT('SIGN') // 打印初始化 PRINT_INIT(打印任务名)
      if (this.form.printCode && this.form.printCode !== 'null') {
        LODOP.SET_PRINTER_INDEXA(this.form.printCode)
      }
      // LODOP.ADD_PRINT_PDF(0, 0, "100%", "100%", this.fileAddress);
      LODOP.ADD_PRINT_URL(0, 0, "100%", "100%", 'https://bh-express.cn/prod-api/profile/download/shipment_1712761064508.pdf');
      LODOP.PREVIEW();
    }
  }
}
</script>
